package crud

import (
	"fmt"
	"github.com/emicklei/go-restful"
	"gitlab.com/adapt-karaoke-project/backend/model"
	"net/http"
	"strconv"
	"gitlab.com/adapt-karaoke-project/backend/config"
	"github.com/jinzhu/gorm"
)

var stubRecords = []model.Record{
	model.Record{
		Model: gorm.Model{
			ID: config.IDRecordStub1,
		},
		SongId: config.IDSongStub,
		UserId: config.IDUser1Stub,
		Type: model.RecordTypeUnmodified,
		Record: strconv.Itoa(config.OIDMusicStub),
	},
	model.Record{
		Model: gorm.Model {
			ID: config.IDRecordStub2,
		},
		SongId: config.IDSongStub,
		UserId: config.IDUser2Stub,
		Type: model.RecordTypeUnmodified,
		Record: strconv.Itoa(config.OIDMusicStub),
	},
}

func (cs *CrudService) initStubRecords() {
	for _, record := range stubRecords {
		cs.dbService.DB.Unscoped().Delete(&record)
		cs.dbService.DB.NewRecord(&record)
		cs.dbService.DB.Create(&record)
	}
}

func (cs *CrudService) GetRecords(req *restful.Request, resp *restful.Response) {
	user_str := req.QueryParameter("user")
	original_song_id_str := req.QueryParameter("original-song-id")
	fmt.Printf("User = %v, original_song= %v \n", user_str, original_song_id_str)
	query_record := map[string]interface{}{}
	if user_str != "" {
		user_id, err := strconv.ParseUint(user_str, 10, 0)
		if err != nil {
			resp.WriteError(http.StatusBadRequest, err)
			return
		}
		query_record["user_id"] = uint(user_id)
	}
	if original_song_id_str != "" {
		original_song_id, err := strconv.ParseUint(original_song_id_str, 10, 0)
		if err != nil {
			resp.WriteError(http.StatusBadRequest, err)
			return
		}
		query_record["song_id"] = original_song_id
	}
	var records []model.Record
	cs.dbService.DB.Where(query_record).Find(&records)
	resp.WriteEntity(records)
}

func (cs *CrudService) GetRecordById(req *restful.Request, resp *restful.Response) {
	record_id_str := req.PathParameter("record-id")
	record_id, err := strconv.ParseUint(record_id_str, 10, 0)
	if err != nil {
		resp.WriteError(http.StatusBadRequest, err)
		return
	}
	var record model.Record
	cs.dbService.DB.First(&record, record_id)
	if record.ID == 0 {
		resp.WriteErrorString(http.StatusNotFound, "No such record")
		return
	}
	resp.WriteEntity(record)
}

func (cs *CrudService) PostRecordStub(req *restful.Request, resp *restful.Response) {
	resp.WriteHeader(http.StatusOK)
}
